package net.llz.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import net.llz.config.WeChatConfig;
import net.llz.dto.VideoOrderDto;
import net.llz.mapper.UserMapper;
import net.llz.mapper.VideoMapper;
import net.llz.mapper.VideoOrderMapper;
import net.llz.model.UserDO;
import net.llz.model.VideoDO;
import net.llz.model.VideoOrderDO;
import net.llz.service.VideoOrderService;
import net.llz.util.CommonUtils;
import net.llz.util.HttpUtils;
import net.llz.util.WXPayUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
@Slf4j
public class VideoOrderServiceImpl implements VideoOrderService {

    @Autowired
    private VideoOrderMapper videoOrderMapper;

    @Autowired
    private VideoMapper videoMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WeChatConfig weChatConfig;


    private Logger logger = LoggerFactory.getLogger(this.getClass());

    private Logger dataLogger = LoggerFactory.getLogger("dataLogger");
    /**
     * 保存订单
     * @param videoOrderDto
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED )

    public String  saveVideoOrder(VideoOrderDto videoOrderDto) throws Exception {

        dataLogger.info("module=video_order`api=save`user_id={}`video_id={}",
                videoOrderDto.getUserId(),videoOrderDto.getVideoId());


        //查找视频信息
        VideoDO videoDO= videoMapper.selectById(videoOrderDto.getId());
        //查找用户信息
        UserDO userDO =userMapper.selectById(videoOrderDto.getUserId());
        //生成订单

        VideoOrderDO videoOrderDO = new VideoOrderDO();
        videoOrderDO.setTotalFee(videoDO.getPrice());
        videoOrderDO.setVideoImg(videoDO.getCoverImg());
        videoOrderDO.setCreateTime(new Date());
        videoOrderDO.setVideoImg(videoDO.getCoverImg());
        videoOrderDO.setVideoId(videoDO.getId());
        videoOrderDO.setState(0);
        videoOrderDO.setDel(0);

        videoOrderDO.setUserId(userDO.getId());
        videoOrderDO.setHeadImg(userDO.getHeadImg());
        videoOrderDO.setNickname(userDO.getName());

        videoOrderDO.setIp(videoOrderDto.getIp());
        videoOrderDO.setOutTradeNo(CommonUtils.generateUUID());

        videoOrderMapper.insert(videoOrderDO);


        //获取codeurl
        String codeUrl = unifiedOrder(videoOrderDO);


        //生成二维码


        return codeUrl;

    }
    /**
     * 统一下单方法
     * @return
     */
    public String  unifiedOrder(VideoOrderDO videoOrderDO) throws Exception {
        //生成签名
        SortedMap<String,String> params = new TreeMap<>();
        params.put("appid", weChatConfig.getAppId());
        params.put("mch_id", weChatConfig.getMchId());
        params.put("nonce_str",CommonUtils.generateUUID());
        params.put("body",videoOrderDO.getVideoTitle());
        params.put("out_trade_no",videoOrderDO.getOutTradeNo());
        params.put("total_fee",videoOrderDO.getTotalFee().toString());
        params.put("spbill_create_ip",videoOrderDO.getIp());
        params.put("notify_url",weChatConfig.getPayCallbackUrl());
        params.put("trade_type","NATIVE");
        //sign签名
        String sign = WXPayUtil.createSign(params,weChatConfig.getKey());
        params.put("sign",sign);
        //map转xml
        String mapXml = WXPayUtil.mapToXml(params);
        System.out.println(mapXml);
        //统一下单
        String orderStr= HttpUtils.doPost(WeChatConfig.getUnifiedOrderUrl(),mapXml,4000);
        if (orderStr==null){
            return null;
        }

        Map<String,String> unifiedOrderMap= WXPayUtil.xmlToMap(orderStr);
        System.out.println(unifiedOrderMap.toString());
        if(unifiedOrderMap!=null){
            return unifiedOrderMap.get("code_url");
        }

        return  null;
    }

    /**
     * 根据id查找订单
     * @param id
     * @return
     */
    @Override
    public VideoOrderDO findById(int id) {

        return videoOrderMapper.selectById(id);
    }


    /**
     * 根据流水好查找
     * @param outTradeNo
     * @return
     */
    @Override
    public VideoOrderDO findByOutTradeNo(String outTradeNo) {

        VideoOrderDO videoOrderDO   = videoOrderMapper.selectOne(new QueryWrapper<VideoOrderDO>()
                .eq("outTradeNo",outTradeNo).eq("del",0));
        return videoOrderDO;
    }

    /**
     * 逻辑删除订单
     * @param id
     * @return
     */
    @Override
    public int del(int id) {
//        VideoOrderDO videoOrderDO = new VideoOrderDO();
//        videoOrderDO.setDel(0);
//        int upd = videoOrderMapper.update(videoOrderDO,new QueryWrapper<VideoOrderDO>().eq("id",id));
        int delrows = videoOrderMapper.deleteById(id);
        return delrows;
    }

    /**
     * 根据userID
     * @param userId 返回所有订单
     * @return
     */
    @Override
    public List<VideoOrderDO> findMyOrderList(int userId) {

        List<VideoOrderDO> list = videoOrderMapper.selectList(new QueryWrapper<VideoOrderDO>()
                .eq("userId",userId));
        return list;
    }

    /**
     * 根据订单号更新
     * @param videoOrderDO
     * @return
     */
    @Override
    public int updateVideoOderByOutTradeNo(VideoOrderDO videoOrderDO) {

        return videoOrderMapper.updateById(videoOrderDO);
    }
}
